package com.eudon.ai.agent.tools;

import cn.hutool.core.io.FileUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;

import static com.eudon.ai.agent.common.Constants.FILES_ROOT_DIR;
import static com.eudon.ai.agent.common.Constants.FILE_DIR_SEPARATOR;

/**
 * @author eudon
 * @description Spring AI框架ChatModel调用时使用的文件读取写入Tool
 * @date 2025/8/19
 * @email syd19970616@gmail.com
 * @address <a href="https://gitee.com/eudon">Gitee</a>
 */
public class FileOperationTool {
    @Tool(description = "read content from file")
    public String readFile(@ToolParam(description = "the dir of file", required = false) String fileDir,
                           @ToolParam(description = "file`s name") String fileName) {
        fileDir = getFileDir(fileDir);
        String filePath = getFilePath(fileDir, fileName);
        String fileContent;
        try {
            fileContent = FileUtil.readUtf8String(filePath);
        } catch (Exception e) {
            return "read file error,caused by: " + e.getMessage();
        }
        // 实现文件读取逻辑
        return fileContent;
    }

    @Tool(description = "write content to file")
    public String writeFile(@ToolParam(description = "the dir of file", required = false) String fileDir,
                            @ToolParam(description = "file`s name") String fileName,
                            @ToolParam(description = "file`s content") String content) {
        fileDir = getFileDir(fileDir);
        String filePath = getFilePath(fileDir, fileName);

        try {
            FileUtil.mkdir(fileDir);
            FileUtil.writeUtf8String(content, filePath);
        } catch (Exception e) {
            return "tell user : write file error,caused by:" + e.getMessage();
        }

        return "tell user : write file success,filename:" + fileName + ",filepath:" + fileDir;
    }

    private String getFilePath(String fileDir, String fileName) {
        return fileDir.concat(FILE_DIR_SEPARATOR).concat(fileName);
    }

    private String getFileDir(String fileDir) {
        return StringUtils.isBlank(fileDir) ? FILES_ROOT_DIR : fileDir;
    }
}
